/**
 * Copyright (C), 2015-2018, XXX有限公司
 * FileName: JokeServiceImpl
 * Author:   臧浩鹏
 * Date:     2018/8/6 9:21
 * Description: Joke的实现类
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.etc.service.impl;

import com.etc.common.Const;
import com.etc.common.ServerResponse;
import com.etc.dao.JokeMapper;
import com.etc.dao.UserMapper;
import com.etc.entity.Joke;
import com.etc.entity.User;
import com.etc.service.JokeService;
import com.etc.service.TalkService;
import com.etc.utils.DateTimeUtil;
import com.etc.vo.JokeVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 〈一句话功能简述〉<br> 
 * 〈Joke的实现类〉
 *
 * @author 臧浩鹏
 * @create 2018/8/6
 * @since 1.0.0
 */
@Service
public class JokeServiceImpl implements JokeService{

    private static final Logger log = Logger.getLogger(JokeServiceImpl.class);
    @Autowired
    private JokeMapper jokeMapper;
    @Autowired
    private TalkService talkService;
    @Autowired
    private UserMapper userMapper;
    /**
     *
     * @Description: 插入笑话
     *
     * @auther: 臧浩鹏
     * @date: 10:22 2018/8/7
     * @param: [joke, pageNum, pageSize]
     * @return: com.etc.common.ServerResponse<com.github.pagehelper.PageInfo>
     *
     */
    @Override
    public ServerResponse<PageInfo> insertJoke(Joke joke, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        int res = jokeMapper.insert(joke);
        if(res > 0){
            List<Joke> jokes = listByjcategory(joke.getjUid(),null);
            PageInfo pageInfo = new PageInfo(jokes);
            log.info("用户："+joke.getjUid()+"创建笑话成功！"+"joke Id 为："+joke.getJid()+"joke 内容："+joke.getJdesc());
            return ServerResponse.createBySuccess(pageInfo);
        }
        log.info("用户："+joke.getjUid()+"创建笑话失败！"+"joke Id 为："+joke.getJid()+"joke 内容："+joke.getJdesc());
        return ServerResponse.createByErrorMessage("插入joke失败！");
    }
    /**
     *
     * @Description: 删除时 只有该文章所属用户与管理员才有权限
     *
     * @auther: 臧浩鹏
     * @date: 10:31 2018/8/7
     * @param: [joke, uid]
     * @return: com.etc.common.ServerResponse
     *
     */
    @Override
    public ServerResponse deleteJoke(Integer jid){
        int count = jokeMapper.deleteByPrimaryKey(jid);
        if (count>0){
            return ServerResponse.createBySuccess("删除成功！");
        }
        return ServerResponse.createByErrorMessage("删除失败！请查看日志！");
    }

    @Override
    public ServerResponse<JokeVo> selectOneByjid(Integer jid){
        Joke joke = jokeMapper.selectByPrimaryKey(jid);
        if (joke == null){
            return ServerResponse.createByErrorMessage("不存在该joke");
        }
        JokeVo jokeVo = new JokeVo();
        List<List> res = searchAllLikeAndUnlike(joke.getJid());
        jokeVo.setJlike(String.valueOf(res.get(0).size()));
        jokeVo.setJunlike(String.valueOf(res.get(1).size()));
        return ServerResponse.createBySuccess(jokeVo);
    }

    /**
     * 该方法可供用户与管理员control调用
     * 	当为用户时 应当判断其自己的id来查找 普通的浏览时要传jcategory
     * 	当为管理员时，参数为空时全查出来，提倡根据分类ID查询，可查询某用户的joke信息
     * @param uid
     * @param jcategory
     * @return jokes
     */
    private List<Joke> listByjcategory(Integer uid ,Integer jcategory){
        if (jcategory == 0){
            jcategory = null;
        }
        if (uid == 0){
            uid = null;
        }
        return jokeMapper.selectAllByJcategory(uid,jcategory);
    }

    @Override
    public ServerResponse selectByJcategory(Integer uid, Integer jcategory, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Joke> jokes = listByjcategory(uid, jcategory);
        List<JokeVo> jokeVos = Lists.newArrayList();
        for(Joke joke : jokes){
            JokeVo jokeVo = new JokeVo();
            List<List> res = searchAllLikeAndUnlike(joke.getJid());
            jokeVo.setJlike(String.valueOf(res.get(0).size()));
            jokeVo.setJunlike(String.valueOf(res.get(1).size()));
            Integer comments = talkService.selectNumsByCidAndAid(Const.Category.JOKE,joke.getJid());
            jokeVo.setComments(comments);
            jokeVo.setJcategory(jcategory);
            jokeVo.setJdesc(joke.getJdesc());
            jokeVo.setJimg(joke.getJimg());
            jokeVo.setJstatus(joke.getJstatus());
            User user = userMapper.selectByPrimaryKey(joke.getjUid());
            if(user == null){
                jokeVo.setJauthor("佚名");
            }
            jokeVo.setJcreatetime(DateTimeUtil.randomDate());
            jokeVo.setUimg(user.getUimg());
            jokeVo.setJauthor(user.getUname());
            jokeVo.setJid(joke.getJid());
            jokeVos.add(jokeVo);
        }
        PageInfo pageInfo = new PageInfo(jokes);
        pageInfo.setList(jokeVos);
        return ServerResponse.createBySuccess(pageInfo);
    }


    /**
     * 该方法仅管理员control调用
     * 	当为管理员时，参数为空时全查出来，根据审核状态查找
     * @param Status
     * @return jokes
     */

    @Override
    public ServerResponse selectByStatus(Integer Status, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Joke> jokes = jokeMapper.selectByStatus(Status);
        System.out.println(jokes);
        List<JokeVo> jokeVos = packJokes(jokes);
        PageInfo pageInfo = new PageInfo(jokes);
        pageInfo.setList(jokeVos);
        return ServerResponse.createBySuccess(pageInfo);
    }

    /**
     *
     * @Description: 用于批量删除
     *
     * @auther: 臧浩鹏
     * @date: 13:58 2018/8/11
     * @param: [jids]
     * @return: com.etc.common.ServerResponse
     *
     */
    @Override
    public ServerResponse deleteJokeByBatch(String[] jids) {
        int[] ints = new int[jids.length];
        for(int i = 0;i<ints.length;i++){
            ints[i] = Integer.parseInt(jids[i]);
        }
        Integer count = jokeMapper.deleteByBatch(ints);
        if (count>0){
            return ServerResponse.createBySuccess("删除了"+count+"条数据");
        }
        return ServerResponse.createByErrorMessage("删除失败！具体原因请查看日志！");
    }

    private List<JokeVo> packJokes(List<Joke> jokes){
        List<JokeVo> jokeVos = Lists.newArrayList();
        for(Joke joke : jokes){
            JokeVo jokeVo = new JokeVo();
            List<List> res = searchAllLikeAndUnlike(joke.getJid());
            jokeVo.setJlike(String.valueOf(res.get(0).size()));
            jokeVo.setJunlike(String.valueOf(res.get(1).size()));
            Integer comments = talkService.selectNumsByCidAndAid(Const.Category.JOKE,joke.getJid());
            jokeVo.setComments(comments);
            jokeVo.setJcategory(joke.getJcategory());
            jokeVo.setJdesc(joke.getJdesc());
            jokeVo.setJimg(joke.getJimg());
            jokeVo.setJstatus(joke.getJstatus());
            User user = userMapper.selectByPrimaryKey(joke.getjUid());
            if(user == null){
                jokeVo.setJauthor("佚名");
            }
            jokeVo.setJcreatetime(DateTimeUtil.randomDate());
            jokeVo.setUimg(user.getUimg());
            jokeVo.setJauthor(user.getUname());
            jokeVo.setJid(joke.getJid());
            jokeVos.add(jokeVo);
        }
        return jokeVos;
    }



    /**
     * 更新joke的like unlike字段 进行增加uid 或去除uid
     * @param jid
     * @param attitude
     * @param uid2
     * @return
     */
    @Override
    public ServerResponse<List<List>> judgeAndHandleAttitude(Integer jid, Integer attitude, Integer uid2) {
        String uid = String.valueOf(uid2);
        List<List> res = searchAllLikeAndUnlike(jid);
        //先判断是点赞还是点灭：
        List<String> flag1 = res.get(0);
        List<String> flag2 = res.get(1);
        if (attitude == Const.Attitude.LIKE) {
            if (flag1.contains(uid)) {
                //包含则说明以点过赞：进行取消点赞操作
                flag1.remove(uid);
                //计算此时的点赞数
                int likes = res.get(0).size();
            } else if (flag2.contains(uid)) {
                //包含则说明之前是点灭 现在要进行点赞操作:先进行点灭减一，去除掉此ID
                flag2.remove(uid);
                flag1.add(uid);
                //计算此时的点赞数
                int likes = res.get(0).size();
                //此时的点赞人id 及 点灭人id ： res.get(0)  ;  res.get(1)

            }else {
                //都没有则说明是第一次点赞：直接进行like + 1；
                flag1.add(uid);
            }

        }
        if (attitude == Const.Attitude.UNLIKE) {
            if (flag2.contains(uid)) {
                //包含则说明以点过踩：进行取消点踩操作
                flag2.remove(uid);
                //计算此时的点赞数
                int likes = flag1.size();
            } else if (flag1.contains(uid)) {
                //包含则说明之前是点赞 现在要进行点踩操作:先进行点赞减一，去除掉此ID
                flag1.remove(uid);
                flag2.add(uid);
                //计算此时的点踩数
                int likes = flag2.size();
                //此时的点赞人id 及 点灭人id ： res.get(0)  ;  res.get(1)

            }else {
                //都没有则说明是第一次点踩：直接进行unlike + 1；
                flag2.add(uid);
            }
        }
        //更新数据库中该joke的信息
        Joke joke = new Joke();
        joke.setJid(jid);
        System.out.println(flag1);
        System.out.println(flag2);
        String like = "";
        String unlike = "";
        for(String s : flag1){
            like+=(s+",");
        }
        for(String s : flag2){
            unlike+=(s+",");
        }
        joke.setJlike(like);
        joke.setJunlike(unlike);
        int rescount = jokeMapper.updateByPrimaryKeySelective(joke);
        if (rescount>0) {
            //进行点赞或点踩成功则直接返回点赞总数 与 点踩总数
            //List<Set<String>> resAll = searchAllLikeAndUnlike(jid);
            res.set(0,flag1);
            res.set(1,flag2);
            return ServerResponse.createBySuccess(res);
        }
        return ServerResponse.createByError();

    }
    /**
     * 此方法为 初始化 将数据库中的like 与 unlike 添加到list<list>中
     * @param jid
     * @return
     */
    private List<List> searchAllLikeAndUnlike(Integer jid){

        List<List> temp = Lists.newArrayList();
        Joke joke = jokeMapper.selectByPrimaryKey(jid);
        if (StringUtils.isBlank(joke.getJlike())) {
            temp.add(new ArrayList());
        }else {
            String[] split = joke.getJlike().split(",");
            List<String> set = new ArrayList<>();
            for (String s : split){
                set.add(s.trim());
            }
            temp.add(set);
        }
        if (StringUtils.isBlank(joke.getJunlike())) {
            temp.add(new ArrayList());
        }else {
            String[] split = joke.getJunlike().split(",");
            List<String> set = new ArrayList<>();
            for (String s : split){
                set.add(s.trim());
            }
            temp.add(set);
        }
        return temp;
    }

    /**
     * 审核joke的方法:初始值为 0 ==> 未审核 ; -1 ==> 审核不通过; 1 ==> 审核通过
     * @param jid
     */
    @Override
    public ServerResponse checkJstatus(Integer jid, Integer status) {
        Joke joke = new Joke();
        joke.setJstatus(String.valueOf(status));
        joke.setJid(jid);
        int res = jokeMapper.updateByPrimaryKeySelective(joke);
        if(res>0){
            //返回审核通过还是没通过
            log.info("更新审核状态成功！"+"jokeId 为："+jid+"===>"+"审核结果为："+status);
            return ServerResponse.createBySuccess("更改状态成功！",status);
        }
        //更新出错!
        log.error("更新审核状态出错！");
        return ServerResponse.createByError();
    }






    /*
     *
     * @Description: V1
     *
     * @auther: 臧浩鹏
     * @date: 7:57 2018/8/7
     * @param: [tcategory, tarticleid]
     * @return: com.etc.vo.TalkVo
     *
    public TalkVo searchTalkAll(String tcategory,Integer tarticleid){
        TalkVo talkVo = new TalkVo();
        talkVo.setUname("root");
        talkVo.setUid(0);
        talkVo.setChildrens(new ArrayList<>());
        this.searchTalkWithDeep(talkVo,tcategory,tarticleid);
        return talkVo;
    }

    private void searchTalkWithDeep(TalkVo talkVo, String tcategory, Integer tarticleid) {
        List<Talk> talks = talkMapper.searchOneLevelTalk(talkVo.getUid(), tcategory, tarticleid);
        for(Talk talk : talks){
            User user = userMapper.selectByPrimaryKey(talk.gettUid());
            TalkVo temp = new TalkVo();
            temp.setUid(user.getUid());
            temp.setUname(user.getUname());
            temp.setUimg(user.getUimg());
            temp.setTtalkinfo(talk.getTcontent());
            talkVo.getChildrens().add(temp);
            searchTalkWithDeep(temp,tcategory,tarticleid);
        }*/

}
